package com.foreveross.bsl.push.web;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 应用异常处理类，可以在此类中分别处理不同的处理，针对不同的异常做展现。
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-7-5
 *
 */
public class ApplicationExceptionsHandler implements HandlerExceptionResolver {
	
	private static final Logger log = LoggerFactory.getLogger(ApplicationExceptionsHandler.class);

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) {
		log.error(ex.getMessage(), ex);
		Map<String, Object> model = new HashMap<String, Object>();  
		model.put("errorMsg", ex.getMessage());
        StringWriter sw=new StringWriter();
        PrintWriter pw=new PrintWriter(sw);
        ex.printStackTrace(pw);
        model.put("stackTrace", sw.toString());
        model.put("ajaxRequest", AjaxUtils.isAjaxRequest(request));
        IOUtils.closeQuietly(pw);
        IOUtils.closeQuietly(sw);
        //TODO 可以根据不同类型的异常构建不同的数据展现不同的异常页面
        response.setStatus(500);
        return new ModelAndView("error/error", model);
	}

}
